#include "drivers.h"
#include "xbee.h"

void RadioInit(void) {
  SPIDrvWrite(0x11,0x80FF);   /* Eliminate Unlock Conditions due to L01 */
  SPIDrvWrite(0x1B,0x8000);   /* Disable TC1. */
  SPIDrvWrite(0x1D,0x8000);   /* Disable TC2. */
  SPIDrvWrite(0x1F,0x8000);   /* Disable TC3. */
  SPIDrvWrite(0x21,0x8000);   /* Disable TC4. */
  if (PTAD_PTAD1) {           // If not a PRO module
    SPIDrvWrite(0x07,0x7C00); // ... Enable single port mode.
  } else {                    // If a PRO module
    SPIDrvWrite(0x07,0x0E00); // ... enable dual port mode.
  }
  SPIDrvWrite(0x0C,0x0300);   /* IRQ pull-up disable. */
  SPIDrvWrite(0x04,0xA08D);   /* New cal value */
  SPIDrvWrite(0x08,0xFFF7);   /* Preferred injection */
  SPIDrvWrite(0x05,0x8351);   /* Acoma, TC1, Doze, ATTN masks, LO1, CRC */
  SPIDrvWrite(0x06,0x4720);   /* CCA, TX, RX, energy detect */
  (void)SPIDrvRead(0x25);
  
  /* Advance the state variable to Idle */
  gu8RTxMode = IDLE_MODE;
  
  Init_Pot();                 // Initialize potentiometer.
  
  PTCD_PTCD7 = 1;             //On/Sleep output, high
  PTCDD_PTCDD7 = 1;
}

void BoostPowerforTx(void) {
  PTDD_PTDD2 = 1;
}

void ReducePowerforRx(void) {
  PTDD_PTDD2 = 0;
}

void Init_Pot() {

  // Make PTA3, PTA4, AND PTD2 outputs.
  PTADD_PTADD3 = 1;   //DIG_POT_CS - Output
  PTADD_PTADD4 = 1;   //Make VDDA/VREF Select Line Output
  PTDDD_PTDDD2 = 1;   //DIG_POT_SRC - Output

  PTAD_PTAD3 = 1;     //DIG_POT_CS High
  PTAD_PTAD4 = 1;     //VDDA/VREF Select High

  POT_Write(INIT_POT);
  
  // Start in receive mode. 
  ReducePowerforRx();
  MC13192_ANT_CTRL2 = ANT_CTRL_ON;    /* Turn on the RX antenna */
  MC13192_ANT_CTRL = ANT_CTRL_OFF;    /* Turn off the TX antenna */
}


void POT_Write(UINT8 value) {
  while(!SPI1S_SPTEF);    //Wait for TX Buffer Empty Flag
  PTAD_PTAD3 = 0;         //DIG_POT_CS low
  SPI1D = value;          // Write Addr byte
  while (!SPI1S_SPTEF);   //Wait again for TX Buffer Empty Flag
  
  
  //A little time is needed after the data
  //is clocked in and before CE is deasserted to allow the POT
  //to operate properly. Each nop is based on a 16 Mhz clock.
  //The amount of time was empirically determined. A timer would be
  //a better option given that the MCU clock could change.
  __asm nop;  __asm nop;  __asm nop;  __asm nop;  __asm nop;
  __asm nop;  __asm nop;  __asm nop;  __asm nop;  __asm nop;
  
  // Bob says the datasheet says no time is needed 
  // between data clock in and CE deassert.
  
  // set A3/DIG_POS_~CS high to disable writing to the digital potentiometer
  // as CS rises, the digital pot loads its register with the clocked in byte value
  PTAD_PTAD3 = 1;     //DIG_POT_CS High
}